"""
Anthropic Claude模型适配器
"""

import anthropic
import json
from typing import Dict, Any, List, Optional
import logging
import asyncio
from .base_adapter import BaseModelAdapter

logger = logging.getLogger(__name__)


class ClaudeAdapter(BaseModelAdapter):
    """Anthropic Claude模型适配器"""

    def __init__(self, api_key: str, model: str = "claude-3-sonnet-20240229"):
        super().__init__(api_key, None, model)
        self.client = anthropic.AsyncAnthropic(api_key=self.api_key)

    async def generate_completion(
        self,
        messages: List[Dict[str, str]],
        temperature: float = 0.2,
        max_tokens: int = 4000,
        timeout: float = 300.0,
        **kwargs
    ) -> str:
        """生成文本完成"""
        try:
            # 转换消息格式
            claude_messages = self._convert_messages_to_claude_format(messages)

            # 提取和合并系统消息
            system_messages = []
            filtered_messages = []

            for msg in claude_messages:
                if msg["role"] == "system":
                    system_messages.append(msg["content"])
                else:
                    filtered_messages.append(msg)

            # 合并所有系统消息，确保JSON格式要求不丢失
            system_message = "\n\n".join(
                system_messages) if system_messages else ""

            # 如果系统消息中没有明确的JSON要求，添加一个
            if system_message and "json" not in system_message.lower():
                system_message += "\n\n请确保返回标准的JSON格式。"

            # 调用Claude API
            response = await self.client.messages.create(
                model=self.model,
                max_tokens=max_tokens,
                temperature=temperature,
                system=system_message if system_message else "你是一个专业的AI助手。",
                messages=filtered_messages
            )

            if not response.content:
                raise Exception("Claude返回空内容")

            # Claude返回的是TextBlock列表
            content = ""
            for block in response.content:
                if hasattr(block, 'text'):
                    content += block.text

            logger.info(f"Claude API调用成功，返回内容长度: {len(content)}")
            return content

        except Exception as e:
            logger.error(f"Claude API调用失败: {str(e)}")
            raise

    def _convert_messages_to_claude_format(self, messages: List[Dict[str, str]]) -> List[Dict[str, str]]:
        """将消息格式转换为Claude格式"""
        claude_messages = []

        for message in messages:
            role = message.get("role", "")
            content = message.get("content", "")

            # Claude支持的角色：system, user, assistant
            if role in ["system", "user", "assistant"]:
                claude_messages.append({
                    "role": role,
                    "content": content
                })

        return claude_messages

    def get_provider_name(self) -> str:
        """获取提供商名称"""
        return "Anthropic Claude"

    def get_supported_models(self) -> List[str]:
        """获取支持的模型列表"""
        # Claude适配器支持任意Claude模型名称
        # 返回常见的模型作为参考，但不限制使用其他Claude模型
        common_models = [
            # Claude 3系列
            "claude-3-opus-20240229",
            "claude-3-sonnet-20240229",
            "claude-3-haiku-20240307",
            "claude-3-5-sonnet-20241022",
            "claude-3-5-haiku-20241022",
            # Claude 2系列
            "claude-2.1",
            "claude-2.0",
            "claude-instant",
            # 未来Claude模型
            "claude-4",
            "claude-4-opus",
            "claude-4-sonnet",
            "claude-4-haiku",
            "claude-3-opus-20241201",
            "claude-3-sonnet-20241201",
            "claude-3-haiku-20241201",
            # 可能的新版本格式
            "claude-3.5-opus",
            "claude-3.5-ultra"
        ]

        # 如果当前模型不在常见列表中，也添加进去（支持未来模型）
        if self.model and self.model not in common_models:
            common_models.append(self.model)
            logger.info(f"添加未知Claude模型到支持列表: {self.model}")

        return common_models

    def validate_config(self) -> bool:
        """验证配置是否有效"""
        if not self.api_key or self.api_key.strip() == "":
            logger.error("Claude API密钥未配置")
            return False

        if not self.model or self.model.strip() == "":
            logger.error("Claude模型名称未配置")
            return False

        # 检查是否为占位符
        placeholder_keys = ["your-claude-api-key-here", "your-api-key-here"]
        if self.api_key in placeholder_keys:
            logger.error("检测到Claude API密钥为占位符，请配置真实的API密钥")
            return False

        # 检查API密钥格式（Claude API密钥通常以sk-ant-开头）
        if not self.api_key.startswith("sk-ant-") and len(self.api_key) < 50:
            logger.warning(f"Claude API密钥格式可能不正确: {self.api_key[:10]}...")

        return True
